public without sharing class SalesInvoiceReportController {
	public Boolean isErr {get;set;}


	public User u ;//当前用户

	public String accJson {get;set;}//可以查看的客户的pk ;

	public String sql {get;private set;} ///有权限的sql ;

	public String countSql {get;private set;}

    public String  CompanyJson {get;private set;}

    public Boolean isSeeAll {get;private set;}

    public Boolean isSubCompanyRight {get;private set;}

    public Boolean isSaleRight {get;private set;}

    public String yearsJson {get;private set;}

    public SalesInvoiceReportController() {
        accJson = '';
        yearsJson = '[]';
        
    }

    public void init(){

    	u  = [select Id,Name, Profile.Name,UserRole.Name,SubCompany__c,UserDepartment__c from User where Id=:UserInfo.getUserId()];
        isSeeAll = getRight(Label.SalesInvoiceAllRight);
        isSubCompanyRight = getRight(Label.SalesInvoiceSubRight);
        isSaleRight = getRight(Label.SalesInvoiceSalerRight);
    	if(isSaleRight || isSubCompanyRight ||  isSeeAll){
    		//销售员
    	}else{
    		setError('没有权限查看!');
    		return ;
    	}
        getYears();
        
        if(!isSeeAll && !isSubCompanyRight)isSaleRight = true;
    	getAccounts();
        getRetrunCompany();
        //CompanyJson = EncodingUtil.urlEncode(JSON.serialize(companyMap), 'UTF-8') ;
    }


    public Boolean getRight(String right){

        if(right != null){
            for(String r : right.split(',',-1)){
                if(r == u.Profile.Name) return true;
                if(r == u.Name) return true;
               

            }
        }
        return false;
    }
    public void getYears(){
        Set<String> ys = new Set<String>();
       for(AggregateResult arg:  [select Year__c from SalesInvoiceMonthDetail__c where Year__c != null Group by Year__c]){
            ys.add(String.valueOf(arg.get('Year__c')));
       }
       yearsJson = EncodingUtil.urlEncode(JSON.serialize(ys), 'UTF-8');
    }
    public void setError(String message){
    	isErr = true;
    	ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,message));
    }
    ///获取当前用户的所有客户
    ///Owner 和客户协同小组中角色为 :同客户多人负责 销售绩效分配客户权限
    public void getAccounts(){


        Map<String,String> accMap = new Map<String,String>();
    	Set<Id>  salerSet = new Set<Id>();


    	//1.找到所有销售员
    	for(User saler: [select Id from User where ManagerId =:u.Id]){
    		salerSet.add(saler.Id);
    	}
    	//再加上自己
    	salerSet.add(u.Id);
    	//1.找到所有当用户负责的客户
    	for(Account acc :[select Id ,NCICCode__c ,Owner.Name,Name from Account where OwnerId In:salerSet]){
    		if(acc.NCICCode__c != null )accMap.put(acc.NCICCode__c,acc.Name);
           
    	}
    	//2.找到协同小组中包含当前用户的客户
    	for(AccountTeamMember at : [select Id ,user.Name,AccountId,Account.NCICCode__c ,Account.Name from AccountTeamMember where userId in:salerSet and teammemberrole in ('同客户多人负责','销售绩效分配客户权限')]){
    		if(at.Account.NCICCode__c != null)accMap.put(at.Account.NCICCode__c,at.Account.Name);
    	}
    	setSql(accMap.keySet());
    	accJson = EncodingUtil.urlEncode(JSON.serialize(accMap), 'UTF-8'); 

    }
    //获取子公司对应的公司缩写
    public String getRetrunCompany(){
    	Map<String ,String> comMap = new Map<String,String>();
    	for(String com : Label.ShortCompanyName.split(',',-1)){
    		List<String> cs = com.split('-',-1);
    		if(cs != null && cs.size() > 1)comMap.put(cs[0],cs[1]);
    	}
        CompanyJson = EncodingUtil.urlEncode(JSON.serialize(comMap), 'UTF-8') ;

    	//获取公司编码
		return comMap.get(ImportObject.getPicklistValues('Contract__c','Corpcode__c',false).get(u.SubCompany__c));    	
    }

    //获取销售员的大区
    public String getReturnArea(){
        if(u.SubCompany__c == '迈克生物股份有限公司' ){
            String dept = (u.UserDepartment__c  == null ? ''  :u.UserDepartment__c ) + u.UserRole.Name;
           
                if( dept.contains('东区')){
                    return '东区';
                }else if(dept.contains('西区')){
                    return '西区';
                }else if(dept.contains('北区')){
                    return '北区';
                }else if(dept.contains('中区')){
                    return '中区';
                }else if(dept.contains('南区')){
                    return '南区';
                }  
            
        
        }
        return null;
    }


    public void setSql(Set<String> nset ){


    	String s = JSON.serialize(nset);
    	s = s.replaceAll('"','\'');
		s = s.replace('[','(');
		s = s.replace(']',')');
		System.debug(s);

		 sql = 'select Id,Product__r.NCinvshortname__c,Product__r.TypeName__c, Product__r.Category1__c,Product__r.Category2__c,Nccode__c,BudgetProducts__c,AccountPK__c,Product__r.Name ,Product__r.ProductName__c ,Account__r.Name ,Product__r.Brand__c,Year__c ';
         sql += '  ,Project__c, ProductLine__c, SpecialItem__c ,Product__r.Spec__c,Company__c,ReturnCompany__c  ,Account__r.Owner.Name ,Product__r.SerialNo__c,Province__c ,IsTrack__c   ';
		for (Integer i = 1; i <=12; i++) {
			sql += ' ,InvoiceNumber'+i+'__c,InvoiceValueFree'+i+'__c,InvoiceValue'+i+'__c ' ;
		}
		sql += ' from SalesInvoiceMonthDetail__c  where   AccountPK__c != null ';

        countSql = 'select count() from  SalesInvoiceMonthDetail__c where  AccountPK__c != null ' ;

        if(isSeeAll)return;

        String rec = getRetrunCompany();
        String area = getReturnArea();

        if(rec == null){
            setError('子公司信息异常!请联系管理员维护!');
            return;
        }

        if(isSubCompanyRight){
            Map<String,String > companyMap = ImportObject.getPicklistValues('SalesInvoiceMonthDetail__c','Company__c',false);

            String comcode = companyMap.get(u.SubCompany__c);
            if(u.SubCompany__c == '迈克生物股份有限公司' ){
                if(area != null){//如果是迈克生物 大区 子公司经理 
                     sql += '  and ReturnCompany__c in (\''+area+'\' )';  
                    countSql += '  and ReturnCompany__c in (\''+area+'\' )';  
                }else{
                     sql += '  and (ReturnCompany__c in (\''+rec+'\' , \'东区\', \'西区\', \'南区\', \'北区\', \'中区\' )  or Company__c  = \''+comcode+'\')';  
                    countSql += '  and (ReturnCompany__c in (\''+rec+'\' , \'东区\', \'西区\', \'南区\', \'北区\', \'中区\' )  or Company__c  = \''+comcode+'\')';    
                }
              
            }else{

               sql += '  and ( ReturnCompany__c = \''+rec+'\' or Company__c  = \''+comcode+'\') ' ; 
               countSql +=  '  and ( ReturnCompany__c = \''+rec+'\' or Company__c  = \''+comcode+'\') '; 

            }


           
            return;
        }

        if(nset.size() != 0){
            sql += ' and AccountPK__c in ' + s ;
            countSql += ' and AccountPK__c in ' + s ;

        }else{
            setError('没有数据!');
        }
		
        ///归口公司
		if(rec != null && area == null ){

			 sql += '  and ReturnCompany__c = \''+rec+'\'';
			 countSql += ' and  ReturnCompany__c = \''+rec+'\'';
		}else if(area != null && rec != null){
            sql += ' and (ReturnCompany__c = \''+rec+'\' or ReturnCompany__c = \''+area +'\') ';
            countSql += ' and (ReturnCompany__c = \''+rec+'\' or ReturnCompany__c = \''+area +'\') ';
        }


    }


}